<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
// use Intervention\Image\Facades\Image; // 改用原生 GD 库
use Illuminate\Support\Facades\Artisan;
use Exception;

class ImageController extends Controller
{
    /**
     * 批量生成缩略图
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function generateThumbnails(Request $request): JsonResponse
    {
        try {
            $thumbnailSize = 100; // 缩略图尺寸
            
            // 遍历 public 存储下所有一级目录，排除 *_small
            $disk = Storage::disk('public');
            $baseDirs = $disk->directories('');
            $sourceDirs = [];
            foreach ($baseDirs as $dir) {
                if (preg_match('/_small$/', $dir)) {
                    // 已是缩略图目录，跳过
                    continue;
                }
                $sourceDirs[] = $dir;
            }
            // 明确包含常用目录（若存在）：images、store
            foreach (['images', 'store'] as $dir) {
                if (!in_array($dir, $sourceDirs) && $disk->exists($dir)) {
                    $sourceDirs[] = $dir;
                }
            }
        
            if (count($sourceDirs) === 0) {
                Log::info('public 存储无可处理目录或目录均为 *_small，跳过');
                return response()->json([
                    'code' => 0,
                    'message' => '没有找到需要处理的图片目录',
                    'data' => [
                        'total_files' => 0,
                        'processed_files' => 0,
                        'failed_files' => 0,
                        'processed_dirs' => []
                    ]
                ]);
            }
        
            Log::info('开始批量生成缩略图', [
                'source_dirs' => $sourceDirs,
                'thumbnail_size' => $thumbnailSize
            ]);
            
            $totalFiles = 0;
            $processedCount = 0;
            $failedCount = 0;
            $failedFiles = [];
            
            // 逐目录处理图片并生成缩略图
            foreach ($sourceDirs as $sourcePath) {
                $targetPath = $sourcePath . '_small';
        
                // 获取该目录下所有图片文件
                $imageFiles = $this->getAllImageFiles($sourcePath);
                $dirTotal = count($imageFiles);
                $totalFiles += $dirTotal;
                
                // 目录级跳过：若目标目录已存在且缩略图数量 >= 源图片数量，则跳过整个目录
                $generatedCountDir = 0;
                if ($disk->exists($targetPath)) {
                    $generatedCountDir = count($this->getAllImageFiles($targetPath));
                }
                if ($dirTotal > 0 && $generatedCountDir >= $dirTotal) {
                    Log::info("目录 {$sourcePath} 缩略图已全部生成（{$generatedCountDir}/{$dirTotal}），跳过");
                    continue;
                }
        
                Log::info("目录 {$sourcePath} 找到 {$dirTotal} 个图片文件需要处理");
        
                foreach ($imageFiles as $index => $imageFile) {
                    try {
                        $this->generateThumbnail($imageFile, $sourcePath, $targetPath, $thumbnailSize);
                        $processedCount++;
        
                        // 每处理100个文件记录一次进度（全局计数）
                        if (($processedCount) % 100 === 0) {
                            Log::info("已处理 {$processedCount}/{$totalFiles} 个文件");
                        }
                    } catch (Exception $e) {
                        $failedCount++;
                        $failedFiles[] = [
                            'file' => $imageFile,
                            'dir' => $sourcePath,
                            'error' => $e->getMessage()
                        ];
                        
                        Log::error("处理图片失败: {$imageFile}", [
                            'dir' => $sourcePath,
                            'error' => $e->getMessage(),
                            'file' => $e->getFile(),
                            'line' => $e->getLine()
                        ]);
                    }
                }
            }
        
            Log::info('缩略图生成完成', [
                'total_files' => $totalFiles,
                'processed_files' => $processedCount,
                'failed_files' => $failedCount
            ]);
            
            return response()->json([
                'code' => 1,
                'message' => '缩略图生成完成',
                'data' => [
                    'total_files' => $totalFiles,
                    'processed_files' => $processedCount,
                    'failed_files' => $failedCount,
                    'failed_file_details' => $failedFiles,
                    'processed_dirs' => $sourceDirs
                ]
            ]);
            
        } catch (Exception $e) {
            Log::error('批量生成缩略图失败', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '缩略图生成失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 异步批量生成缩略图（队列方式）
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function generateThumbnailsAsync(Request $request): JsonResponse
    {
        try {
            $thumbnailSize = 100;
            $disk = Storage::disk('public');
            
            // 源目录列表：public 下所有一级目录（排除 *_small）
            $baseDirs = $disk->directories('');
            $sourceDirs = [];
            foreach ($baseDirs as $dir) {
                if (preg_match('/_small$/', $dir)) continue;
                $sourceDirs[] = $dir;
            }
            foreach (['images', 'store'] as $dir) {
                if (!in_array($dir, $sourceDirs) && $disk->exists($dir)) {
                    $sourceDirs[] = $dir;
                }
            }
        
            if (count($sourceDirs) === 0) {
                return response()->json([
                    'code' => 0,
                    'message' => '没有找到需要处理的图片目录',
                    'data' => null
                ]);
            }
        
            Log::info('提交缩略图任务到队列', [
                'source_dirs' => $sourceDirs,
                'thumbnail_size' => $thumbnailSize
            ]);
        
            $totalFiles = 0;
            $submittedJobs = 0;
            $skippedDirs = [];
        
            foreach ($sourceDirs as $sourcePath) {
                $targetPath = $sourcePath . '_small';
                $imageFiles = $this->getAllImageFiles($sourcePath);
                $dirTotal = count($imageFiles);
                $totalFiles += $dirTotal;
        
                // 目录级跳过：缩略图数量 >= 源图片数量
                $generatedCountDir = 0;
                if ($disk->exists($targetPath)) {
                    $generatedCountDir = count($this->getAllImageFiles($targetPath));
                }
                if ($dirTotal > 0 && $generatedCountDir >= $dirTotal) {
                    $skippedDirs[] = $sourcePath;
                    Log::info("目录 {$sourcePath} 已全部生成，跳过队列提交");
                    continue;
                }
        
                foreach ($imageFiles as $imageFile) {
                    // 构建目标文件路径
                    $targetFile = str_replace($sourcePath, $targetPath, $imageFile);
                    // 仅对缺失的缩略图提交任务
                    if (!$disk->exists($targetFile)) {
                        \App\Jobs\GenerateThumbnailJob::dispatch($imageFile, $sourcePath, $targetPath, $thumbnailSize);
                        $submittedJobs++;
                    }
                }
            }
        
            return response()->json([
                'code' => 1,
                'message' => '缩略图生成任务已提交到队列',
                'data' => [
                    'total_files' => $totalFiles,
                    'submitted_jobs' => $submittedJobs,
                    'skipped_dirs' => $skippedDirs,
                    'queue_name' => 'default',
                    'status' => 'processing'
                ]
            ]);
        } catch (Exception $e) {
            Log::error('提交缩略图生成任务失败', [
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '提交任务失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 获取指定目录下的所有图片文件
     * 
     * @param string $directory
     * @return array
     */
    private function getAllImageFiles(string $directory): array
    {
        $disk = Storage::disk('public');
        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
        $imageFiles = [];
        
        // 递归获取所有文件
        $allFiles = $disk->allFiles($directory);
        
        foreach ($allFiles as $file) {
            $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            if (in_array($extension, $imageExtensions)) {
                $imageFiles[] = $file;
            }
        }
        
        return $imageFiles;
    }
    
    /**
     * 生成单个缩略图
     * 
     * @param string $imageFile
     * @param string $sourcePath
     * @param string $targetPath
     * @param int $size
     * @throws Exception
     */
    private function generateThumbnail(string $imageFile, string $sourcePath, string $targetPath, int $size): void
    {
        $disk = Storage::disk('public');
        
        // 构建目标文件路径，保持目录结构
        $targetFile = str_replace($sourcePath, $targetPath, $imageFile);
        
        // 检查目标文件是否已存在
        if ($disk->exists($targetFile)) {
            Log::info("缩略图已存在，跳过: {$targetFile}");
            return;
        }
        
        // 确保目标目录存在
        $targetDir = dirname($targetFile);
        if (!$disk->exists($targetDir)) {
            $disk->makeDirectory($targetDir, 0755, true);
        }
        
        // 读取原始图片
        $imagePath = $disk->path($imageFile);
        
        if (!file_exists($imagePath)) {
            throw new Exception("原始图片文件不存在: {$imageFile}");
        }
        
        // 使用原生 PHP GD 库生成缩略图（更稳定的方案）
        $targetPath = $disk->path($targetFile);
        $this->generateThumbnailWithGD($imagePath, $targetPath, $size);
        
        Log::debug("缩略图生成成功: {$imageFile} -> {$targetFile}");
    }
    
    /**
     * 获取缩略图生成进度
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function getProgress(Request $request): JsonResponse
    {
        try {
            $disk = Storage::disk('public');
            
            // 源目录列表：public 下所有一级目录（排除 *_small）
            $baseDirs = $disk->directories('');
            $sourceDirs = [];
            foreach ($baseDirs as $dir) {
                if (preg_match('/_small$/', $dir)) continue;
                $sourceDirs[] = $dir;
            }
            foreach (['images', 'store'] as $dir) {
                if (!in_array($dir, $sourceDirs) && $disk->exists($dir)) {
                    $sourceDirs[] = $dir;
                }
            }
        
            $overallTotal = 0;
            $overallGenerated = 0;
            $dirDetails = [];
        
            foreach ($sourceDirs as $sourcePath) {
                $targetPath = $sourcePath . '_small';
                $dirTotal = count($this->getAllImageFiles($sourcePath));
                $dirGenerated = $disk->exists($targetPath) ? count($this->getAllImageFiles($targetPath)) : 0;
                
                $overallTotal += $dirTotal;
                $overallGenerated += $dirGenerated;
        
                $dirDetails[] = [
                    'dir' => $sourcePath,
                    'total_files' => $dirTotal,
                    'generated_files' => $dirGenerated,
                    'remaining_files' => max($dirTotal - $dirGenerated, 0)
                ];
            }
        
            $progress = $overallTotal > 0 ? round(($overallGenerated / $overallTotal) * 100, 2) : 0;
            
            return response()->json([
                'code' => 1,
                'message' => '获取进度成功',
                'data' => [
                    'total_files' => $overallTotal,
                    'generated_files' => $overallGenerated,
                    'progress_percentage' => $progress,
                    'remaining_files' => max($overallTotal - $overallGenerated, 0),
                    'dir_details' => $dirDetails
                ]
            ]);
            
        } catch (Exception $e) {
            Log::error('获取缩略图生成进度失败', [
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '获取进度失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 清理缩略图目录
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function cleanThumbnails(Request $request): JsonResponse
    {
        try {
            $disk = Storage::disk('public');
            $baseDirs = $disk->directories('');
            $cleaned = [];
        
            foreach ($baseDirs as $dir) {
                if (preg_match('/_small$/', $dir)) {
                    if ($disk->exists($dir)) {
                        $disk->deleteDirectory($dir);
                        $cleaned[] = $dir;
                        Log::info("缩略图目录已清理: {$dir}");
                    }
                }
            }
        
            return response()->json([
                'code' => 1,
                'message' => '缩略图目录清理成功',
                'data' => [
                    'cleaned_paths' => $cleaned
                ]
            ]);
        } catch (Exception $e) {
            Log::error('清理缩略图目录失败', [
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '清理失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 重新生成指定文件的缩略图
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function regenerateSingle(Request $request): JsonResponse
    {
        try {
            $imageFile = $request->input('param.image_file');
            $size = $request->input('param.size', 100);
            
            if (!$imageFile) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供图片文件路径',
                    'data' => null
                ]);
            }
            
            $sourcePath = 'images';
            $targetPath = 'images_small';
            
            // 检查源文件是否存在
            $disk = Storage::disk('public');
            if (!$disk->exists($imageFile)) {
                return response()->json([
                    'code' => 0,
                    'message' => '源图片文件不存在',
                    'data' => null
                ]);
            }
            
            // 生成缩略图
            $this->generateThumbnail($imageFile, $sourcePath, $targetPath, $size);
            
            // 构建目标文件路径
            $targetFile = str_replace($sourcePath, $targetPath, $imageFile);
            
            return response()->json([
                'code' => 1,
                'message' => '缩略图重新生成成功',
                'data' => [
                    'source_file' => $imageFile,
                    'target_file' => $targetFile,
                    'size' => $size
                ]
            ]);
            
        } catch (Exception $e) {
            Log::error('重新生成单个缩略图失败', [
                'error' => $e->getMessage(),
                'image_file' => $request->input('param.image_file')
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '重新生成失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 使用 GD 库生成缩略图
     */
    private function generateThumbnailWithGD($sourcePath, $targetPath, $size): void
    {
        // 标准化路径
        $sourcePath = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $sourcePath);
        $targetPath = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $targetPath);
        
        // 检查源文件是否存在
        if (!file_exists($sourcePath)) {
            throw new Exception("源图片文件不存在: {$sourcePath}");
        }
        
        // 获取原始图片信息
        $imageInfo = getimagesize($sourcePath);
        if (!$imageInfo) {
            throw new Exception("无法获取图片信息，文件可能损坏: {$sourcePath}");
        }

        $originalWidth = $imageInfo[0];
        $originalHeight = $imageInfo[1];
        $mimeType = $imageInfo['mime'];

        // 根据 MIME 类型创建图片资源
        switch ($mimeType) {
            case 'image/jpeg':
                $sourceImage = imagecreatefromjpeg($sourcePath);
                break;
            case 'image/png':
                $sourceImage = imagecreatefrompng($sourcePath);
                break;
            case 'image/gif':
                $sourceImage = imagecreatefromgif($sourcePath);
                break;
            case 'image/webp':
                if (function_exists('imagecreatefromwebp')) {
                    $sourceImage = imagecreatefromwebp($sourcePath);
                } else {
                    throw new Exception("WebP 格式不支持");
                }
                break;
            default:
                throw new Exception("不支持的图片格式: {$mimeType}");
        }

        if (!$sourceImage) {
            throw new Exception("无法创建图片资源");
        }

        // 创建缩略图画布
        $thumbnail = imagecreatetruecolor($size, $size);
        
        // 根据图片格式设置背景
        if ($mimeType === 'image/png') {
            // PNG格式：透明背景
            imagealphablending($thumbnail, false);
            imagesavealpha($thumbnail, true);
            $transparent = imagecolorallocatealpha($thumbnail, 0, 0, 0, 127);
            imagefill($thumbnail, 0, 0, $transparent);
        } else {
            // JPG等其他格式：白色背景
            $white = imagecolorallocate($thumbnail, 255, 255, 255);
            imagefill($thumbnail, 0, 0, $white);
        }

        // 计算缩放比例（保持宽高比，居中裁剪）
        $scale = max($originalWidth / $size, $originalHeight / $size);
        $newWidth = $originalWidth / $scale;
        $newHeight = $originalHeight / $scale;
        
        $offsetX = ($size - $newWidth) / 2;
        $offsetY = ($size - $newHeight) / 2;

        // 复制并缩放图片
        imagecopyresampled(
            $thumbnail, $sourceImage,
            $offsetX, $offsetY, 0, 0,
            $newWidth, $newHeight,
            $originalWidth, $originalHeight
        );

        // 保存缩略图
        $success = false;
        switch ($mimeType) {
            case 'image/jpeg':
                $success = imagejpeg($thumbnail, $targetPath, 80);
                break;
            case 'image/png':
                $success = imagepng($thumbnail, $targetPath, 8);
                break;
            case 'image/gif':
                $success = imagegif($thumbnail, $targetPath);
                break;
            case 'image/webp':
                if (function_exists('imagewebp')) {
                    $success = imagewebp($thumbnail, $targetPath, 80);
                }
                break;
        }

        // 清理内存
        imagedestroy($sourceImage);
        imagedestroy($thumbnail);

        if (!$success) {
            throw new Exception("保存缩略图失败: {$targetPath}");
        }
    }
    
    /**
     * 继续生成剩余的缩略图
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function continueRemainingThumbnails(Request $request): JsonResponse
    {
        try {
            $sourcePath = 'images';
            $targetPath = 'images_small';
            $thumbnailSize = 100;
            
            Log::info('开始处理剩余缩略图');
            
            $disk = Storage::disk('public');
            
            // 获取所有原始图片文件
            $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
            $allImageFiles = [];
            
            if ($disk->exists($sourcePath)) {
                $allFiles = $disk->allFiles($sourcePath);
                
                foreach ($allFiles as $file) {
                    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (in_array($extension, $imageExtensions)) {
                        $allImageFiles[] = $file;
                    }
                }
            }
            
            // 找出需要处理的文件，并验证文件有效性
            $remainingFiles = [];
            $problemFiles = [];
            
            foreach ($allImageFiles as $imageFile) {
                $targetFile = str_replace($sourcePath, $targetPath, $imageFile);
                if (!$disk->exists($targetFile)) {
                    // 验证文件是否可用
                    if ($this->validateImageFile($imageFile, $disk)) {
                        $remainingFiles[] = $imageFile;
                    } else {
                        $problemFiles[] = $imageFile;
                    }
                }
            }
            
            $totalRemaining = count($remainingFiles);
            
            if ($totalRemaining === 0) {
                return response()->json([
                    'code' => 1,
                    'message' => '所有有效文件的缩略图已生成完成',
                    'data' => [
                        'total_files' => count($allImageFiles),
                        'valid_files' => count($allImageFiles) - count($problemFiles),
                        'problem_files' => count($problemFiles),
                        'remaining_files' => 0,
                        'submitted_jobs' => 0
                    ]
                ]);
            }
            
            Log::info("找到 {$totalRemaining} 个剩余文件需要处理");
            
            // 分批提交任务到队列
            $batchSize = 50; // 每批50个，避免队列过载
            $submittedCount = 0;
            
            for ($i = 0; $i < $totalRemaining; $i += $batchSize) {
                $batchFiles = array_slice($remainingFiles, $i, $batchSize);
                
                foreach ($batchFiles as $imageFile) {
                    \App\Jobs\GenerateThumbnailJob::dispatch($imageFile, $sourcePath, $targetPath, $thumbnailSize);
                    $submittedCount++;
                }
                
                // 小延迟，避免队列过载
                usleep(100000); // 0.1秒
            }
            
            Log::info("已提交 {$submittedCount} 个剩余任务到队列");
            
            return response()->json([
                'code' => 1,
                'message' => '剩余缩略图任务已提交到队列',
                'data' => [
                    'total_files' => count($allImageFiles),
                    'valid_files' => count($allImageFiles) - count($problemFiles),
                    'problem_files' => count($problemFiles),
                    'remaining_files' => $totalRemaining,
                    'submitted_jobs' => $submittedCount,
                    'batch_size' => $batchSize
                ]
            ]);
            
        } catch (Exception $e) {
            Log::error('处理剩余缩略图失败', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '处理剩余缩略图失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 验证图片文件是否可用
     */
    private function validateImageFile($imageFile, $disk): bool
    {
        try {
            $sourceFilePath = $disk->path($imageFile);
            $normalizedPath = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $sourceFilePath);
            
            // 检查文件是否存在
            if (!file_exists($normalizedPath)) {
                return false;
            }
            
            // 检查文件大小
            $fileSize = filesize($normalizedPath);
            if ($fileSize === 0 || $fileSize < 100) {
                return false;
            }
            
            // 尝试获取图片信息
            $imageInfo = getimagesize($normalizedPath);
            if (!$imageInfo) {
                return false;
            }
            
            // 检查图片尺寸
            if ($imageInfo[0] <= 0 || $imageInfo[1] <= 0) {
                return false;
            }
            
            // 检查MIME类型
            $validMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'];
            if (!in_array($imageInfo['mime'], $validMimeTypes)) {
                return false;
            }
            
            return true;
            
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * 获取有问题的文件列表
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function getProblemFiles(Request $request): JsonResponse
    {
        try {
            $sourcePath = 'images';
            $targetPath = 'images_small';
            
            Log::info('开始检查有问题的文件');
            
            $disk = Storage::disk('public');
            
            // 获取所有原始图片文件
            $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
            $allImageFiles = [];
            
            if ($disk->exists($sourcePath)) {
                $allFiles = $disk->allFiles($sourcePath);
                
                foreach ($allFiles as $file) {
                    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (in_array($extension, $imageExtensions)) {
                        $allImageFiles[] = $file;
                    }
                }
            }
            
            // 分类文件
            $processedFiles = [];
            $remainingFiles = [];
            $problemFiles = [];
            
            foreach ($allImageFiles as $imageFile) {
                $targetFile = str_replace($sourcePath, $targetPath, $imageFile);
                
                if ($disk->exists($targetFile)) {
                    $processedFiles[] = $imageFile;
                } else {
                    // 验证文件是否可用
                    $fileStatus = $this->validateImageFileDetailed($imageFile, $disk);
                    
                    if ($fileStatus['valid']) {
                        $remainingFiles[] = $imageFile;
                    } else {
                        $problemFiles[] = [
                            'file' => $imageFile,
                            'reason' => $fileStatus['reason'],
                            'file_size' => $fileStatus['file_size'],
                            'file_path' => $fileStatus['file_path']
                        ];
                    }
                }
            }
            
            Log::info("文件检查完成", [
                'total_files' => count($allImageFiles),
                'processed_files' => count($processedFiles),
                'remaining_files' => count($remainingFiles),
                'problem_files' => count($problemFiles)
            ]);
            
            return response()->json([
                'code' => 1,
                'message' => '获取有问题文件列表成功',
                'data' => [
                    'summary' => [
                        'total_files' => count($allImageFiles),
                        'processed_files' => count($processedFiles),
                        'remaining_files' => count($remainingFiles),
                        'problem_files' => count($problemFiles),
                        'completion_rate' => round((count($processedFiles) / count($allImageFiles)) * 100, 2)
                    ],
                    'problem_files' => $problemFiles,
                    'remaining_files' => $remainingFiles
                ]
            ]);
            
        } catch (Exception $e) {
            Log::error('获取有问题文件列表失败', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '获取有问题文件列表失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 详细验证图片文件是否可用
     */
    private function validateImageFileDetailed($imageFile, $disk): array
    {
        try {
            $sourceFilePath = $disk->path($imageFile);
            $normalizedPath = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $sourceFilePath);
            
            // 检查文件是否存在
            if (!file_exists($normalizedPath)) {
                return [
                    'valid' => false, 
                    'reason' => '文件不存在',
                    'file_size' => 0,
                    'file_path' => $normalizedPath
                ];
            }
            
            // 检查文件大小
            $fileSize = filesize($normalizedPath);
            if ($fileSize === 0) {
                return [
                    'valid' => false, 
                    'reason' => '文件大小为0',
                    'file_size' => $fileSize,
                    'file_path' => $normalizedPath
                ];
            }
            
            if ($fileSize < 100) {
                return [
                    'valid' => false, 
                    'reason' => '文件太小，可能损坏',
                    'file_size' => $fileSize,
                    'file_path' => $normalizedPath
                ];
            }
            
            // 检查文件扩展名
            $extension = strtolower(pathinfo($imageFile, PATHINFO_EXTENSION));
            $validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
            if (!in_array($extension, $validExtensions)) {
                return [
                    'valid' => false, 
                    'reason' => '不支持的图片格式: ' . $extension,
                    'file_size' => $fileSize,
                    'file_path' => $normalizedPath
                ];
            }
            
            // 尝试获取图片信息
            $imageInfo = getimagesize($normalizedPath);
            if (!$imageInfo) {
                return [
                    'valid' => false, 
                    'reason' => '无法读取图片信息，文件可能损坏',
                    'file_size' => $fileSize,
                    'file_path' => $normalizedPath
                ];
            }
            
            // 检查图片尺寸
            if ($imageInfo[0] <= 0 || $imageInfo[1] <= 0) {
                return [
                    'valid' => false, 
                    'reason' => '图片尺寸无效: ' . $imageInfo[0] . 'x' . $imageInfo[1],
                    'file_size' => $fileSize,
                    'file_path' => $normalizedPath
                ];
            }
            
            // 检查MIME类型
            $validMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'];
            if (!in_array($imageInfo['mime'], $validMimeTypes)) {
                return [
                    'valid' => false, 
                    'reason' => '无效的MIME类型: ' . $imageInfo['mime'],
                    'file_size' => $fileSize,
                    'file_path' => $normalizedPath
                ];
            }
            
            return [
                'valid' => true, 
                'reason' => '文件正常',
                'file_size' => $fileSize,
                'file_path' => $normalizedPath
            ];
            
        } catch (Exception $e) {
            return [
                'valid' => false, 
                'reason' => '验证失败: ' . $e->getMessage(),
                'file_size' => 0,
                'file_path' => ''
            ];
        }
    }
    
    /**
     * 通用：批量生成指定目录的缩略图
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function generateDirectoryThumbnails(Request $request): JsonResponse
    {
        try {
            // 从请求中获取源目录，默认为 images
            $sourcePath = $request->input('param.source_path', 'images');
            // 目标目录自动添加 _small 后缀
            $targetPath = $sourcePath . '_small';
            $thumbnailSize = $request->input('param.size', 100);
            
            Log::info('开始批量生成指定目录缩略图', [
                'source_path' => $sourcePath,
                'target_path' => $targetPath,
                'thumbnail_size' => $thumbnailSize
            ]);
            
            // 获取所有图片文件
            $imageFiles = $this->getAllImageFiles($sourcePath);
            $totalFiles = count($imageFiles);
            
            if ($totalFiles === 0) {
                return response()->json([
                    'code' => 0,
                    'message' => "目录 {$sourcePath} 中没有找到需要处理的图片文件",
                    'data' => [
                        'source_path' => $sourcePath,
                        'target_path' => $targetPath,
                        'total_files' => 0,
                        'processed_files' => 0,
                        'failed_files' => 0
                    ]
                ]);
            }
            
            Log::info("找到 {$totalFiles} 个图片文件需要处理");
            
            $processedCount = 0;
            $failedCount = 0;
            $failedFiles = [];
            
            // 批量处理图片
            foreach ($imageFiles as $index => $imageFile) {
                try {
                    $this->generateThumbnail($imageFile, $sourcePath, $targetPath, $thumbnailSize);
                    $processedCount++;
                    
                    // 每处理50个文件记录一次进度
                    if (($index + 1) % 50 === 0) {
                        Log::info("已处理 {$processedCount}/{$totalFiles} 个文件");
                    }
                    
                } catch (Exception $e) {
                    $failedCount++;
                    $failedFiles[] = [
                        'file' => $imageFile,
                        'error' => $e->getMessage()
                    ];
                    
                    Log::error("处理图片失败: {$imageFile}", [
                        'error' => $e->getMessage()
                    ]);
                }
            }
            
            Log::info('缩略图生成完成', [
                'source_path' => $sourcePath,
                'target_path' => $targetPath,
                'total_files' => $totalFiles,
                'processed_files' => $processedCount,
                'failed_files' => $failedCount
            ]);
            
            return response()->json([
                'code' => 1,
                'message' => '缩略图生成完成',
                'data' => [
                    'source_path' => $sourcePath,
                    'target_path' => $targetPath,
                    'total_files' => $totalFiles,
                    'processed_files' => $processedCount,
                    'failed_files' => $failedCount,
                    'failed_file_details' => $failedFiles
                ]
            ]);
            
        } catch (Exception $e) {
            Log::error('批量生成缩略图失败', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '缩略图生成失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 批量生成商家入驻相关图片的缩略图
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function generateStoreThumbnails(Request $request): JsonResponse
    {
        try {
            $directories = [
                'storefront',      // 门头照
                'license',         // 营业执照
                'store_apply'      // 其他文件
            ];
            
            $thumbnailSize = 100;
            $allResults = [];
            $totalProcessed = 0;
            $totalFailed = 0;
            
            Log::info('开始批量生成商家入驻图片缩略图');
            
            foreach ($directories as $sourcePath) {
                $targetPath = $sourcePath . '_small';
                
                Log::info("处理目录: {$sourcePath}");
                
                // 获取该目录下的所有图片文件
                $imageFiles = $this->getAllImageFiles($sourcePath);
                $totalFiles = count($imageFiles);
                
                if ($totalFiles === 0) {
                    Log::info("目录 {$sourcePath} 中没有图片文件，跳过");
                    $allResults[$sourcePath] = [
                        'total_files' => 0,
                        'processed_files' => 0,
                        'failed_files' => 0,
                        'status' => 'empty'
                    ];
                    continue;
                }
                
                $processedCount = 0;
                $failedCount = 0;
                $failedFiles = [];
                
                // 批量处理图片
                foreach ($imageFiles as $index => $imageFile) {
                    try {
                        $this->generateThumbnail($imageFile, $sourcePath, $targetPath, $thumbnailSize);
                        $processedCount++;
                        
                    } catch (Exception $e) {
                        $failedCount++;
                        $failedFiles[] = [
                            'file' => $imageFile,
                            'error' => $e->getMessage()
                        ];
                        
                        Log::error("处理图片失败: {$imageFile}", [
                            'error' => $e->getMessage()
                        ]);
                    }
                }
                
                $totalProcessed += $processedCount;
                $totalFailed += $failedCount;
                
                $allResults[$sourcePath] = [
                    'target_path' => $targetPath,
                    'total_files' => $totalFiles,
                    'processed_files' => $processedCount,
                    'failed_files' => $failedCount,
                    'failed_file_details' => $failedFiles,
                    'status' => 'completed'
                ];
                
                Log::info("目录 {$sourcePath} 处理完成", [
                    'processed' => $processedCount,
                    'failed' => $failedCount
                ]);
            }
            
            Log::info('所有商家入驻图片缩略图生成完成', [
                'total_processed' => $totalProcessed,
                'total_failed' => $totalFailed
            ]);
            
            return response()->json([
                'code' => 1,
                'message' => '商家入驻图片缩略图生成完成',
                'data' => [
                    'summary' => [
                        'total_processed' => $totalProcessed,
                        'total_failed' => $totalFailed,
                        'directories_count' => count($directories)
                    ],
                    'details' => $allResults
                ]
            ]);
            
        } catch (Exception $e) {
            Log::error('批量生成商家入驻图片缩略图失败', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '缩略图生成失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 异步批量生成商家入驻图片缩略图（队列方式）
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function generateStoreThumbnailsAsync(Request $request): JsonResponse
    {
        try {
            $directories = [
                'storefront',      // 门头照
                'license',         // 营业执照
                'store_apply'      // 其他文件
            ];
            
            $thumbnailSize = 100;
            $totalJobs = 0;
            $directoryStats = [];
            
            Log::info('开始提交商家入驻图片缩略图任务到队列');
            
            foreach ($directories as $sourcePath) {
                $targetPath = $sourcePath . '_small';
                
                // 获取该目录下的所有图片文件
                $imageFiles = $this->getAllImageFiles($sourcePath);
                $fileCount = count($imageFiles);
                
                if ($fileCount === 0) {
                    $directoryStats[$sourcePath] = [
                        'file_count' => 0,
                        'status' => 'empty'
                    ];
                    continue;
                }
                
                // 批量提交队列任务
                foreach ($imageFiles as $imageFile) {
                    \App\Jobs\GenerateThumbnailJob::dispatch($imageFile, $sourcePath, $targetPath, $thumbnailSize);
                    $totalJobs++;
                }
                
                $directoryStats[$sourcePath] = [
                    'target_path' => $targetPath,
                    'file_count' => $fileCount,
                    'status' => 'submitted'
                ];
                
                Log::info("目录 {$sourcePath} 提交了 {$fileCount} 个任务");
            }
            
            Log::info("总共提交 {$totalJobs} 个缩略图任务到队列");
            
            return response()->json([
                'code' => 1,
                'message' => '商家入驻图片缩略图任务已提交到队列',
                'data' => [
                    'total_jobs' => $totalJobs,
                    'queue_name' => 'default',
                    'status' => 'processing',
                    'directory_stats' => $directoryStats
                ]
            ]);
            
        } catch (Exception $e) {
            Log::error('提交商家入驻图片缩略图任务失败', [
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '提交任务失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
    
    /**
     * 判断文件是否为图片
     * 
     * @param string $filename
     * @return bool
     */
    private function isImageFile(string $filename): bool
    {
        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
        $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        return in_array($extension, $imageExtensions);
    }
}
